package api

import (
	"encoding/json"
	"io"
	"log"
	"os"
	"strings"
)

// 函数用于以 "-" 为切割字符串的依据
func checkSplitRuneBy45(r rune) bool {
	return r == 45
}

// 函数用于以 "/" 为切割字符串的依据
func checkSplitRuneBy47(r rune) bool {
	return r == 47
}

// 按位异或计算两个字符数组
func xorOps4Bytes(dest []byte, src []byte) (result []byte) {
	result = make([]byte, len(dest))
	for i := range dest {
		result[i] = dest[i] ^ src[i]
	}
	return result
}

// 初始化局部编码路由表（从路由配置文件中读取）
// 每一行表示前 n-1 个节点上的块编码给第 n 个节点
func initRouteTable() {
	var routeTableReader io.Reader
	routeTableJsonFile, err := os.Open(LOCAL_ENCODE_ROUTE_TABLE_FILE)
	defer func() {
		_ = routeTableJsonFile.Close()
	}()
	if err != nil {
		log.Println("Auto-Load Default Route Table !")
		routeTableReader = strings.NewReader(LOCAL_ENCODE_ROUTE_TABLE_STRING)
	} else {
		log.Println("Loaded Route Table From Configuration !")
		routeTableReader = routeTableJsonFile
	}
	decoder := json.NewDecoder(routeTableReader)
	_ = decoder.Decode(&NODE_ROUTE_TABLE)
	for i := 0; i < len(NODE_ROUTE_TABLE)-1; i++ {
		nrt := NODE_ROUTE_TABLE[i]
		var lcrt []Route
		for j := range nrt {
			lcrt = append(lcrt, Route{nrt[j].Nodeid, nrt[j].Ipaddr})
		}
		LOCAL_CHUNK_ROUTE_TABLE = append(LOCAL_CHUNK_ROUTE_TABLE, lcrt)
	}
}
